import Vuex from "vuex";
import Vue from "vue";

Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    dataList: [],
  },
  getters: {
    //添加getters
    getList: (state) => {
      return { items: state.dataList, total: state.dataList.length };
    },
  },
  mutations: {
    getList (state, payload) {
      let pageNum = payload.pageNum || 1;
      let pageSize = payload.pageSize || 15;


      if (state.dataList.length == 0 && localStorage.getItem("dataList")) {
        state.dataList = JSON.parse(localStorage.getItem("dataList"));
      }

      let totalItems = state.dataList.length;
      let pageItems = [];
      for (
        let i = (pageNum - 1) * pageSize;
        i < (pageNum * pageSize > totalItems ? totalItems : pageNum * pageSize);
        i++
      ) {
        pageItems.push(state.dataList[i]);
      }
      payload.callback({ data: { records: pageItems, total: state.dataList.length } });
    },
    addList (state, payload) {
      payload.id = state.dataList.length + 1;
      state.dataList.unshift(payload);
      localStorage.setItem("dataList", JSON.stringify(state.dataList));
    },
    getItem (state, payload) {
      payload.callback(
        state.dataList.find(x => x.pkId == payload.id)
      );
    },
    detItem (state, payload) {
      let i = state.dataList.indexOf(x => x.pkId == payload.id);
      state.dataList.splice(i, 1);
      localStorage.setItem("dataList", JSON.stringify(state.dataList));

    },
    saveItem (state, payload) {
      let item = state.dataList.find(x => x.id == payload.id);
      Object.keys(item).forEach(key => {
        if (payload[key]) item[key] = payload[key];
      });
      localStorage.setItem("dataList", JSON.stringify(state.dataList));
    }
  },
  actions: {
    //在mock中需要使用同步操作
    getList (context, payload) {
      let pageNum = payload.pageNum || 1;
      let pageSize = payload.pageSize || 15;
      let totalItems = context.state.dataList.length;
      let pageItems = [];
      for (
        let i = (pageNum - 1) * pageSize;
        i < (pageNum * pageSize > totalItems ? totalItems : pageNum * pageSize);
        i++
      ) {
        pageItems.push(context.state.dataList[i]);
      }
      return { items: pageItems, total: context.state.dataList.length };
    },
  },
});

export default store;
